package com.filemanager;

import javax.swing.*;
import javax.swing.tree.*;
import java.awt.event.*;
import java.io.File;

public class FileTreeContextMenu {
    private File clipboardFile = null;
    private boolean isCutOperation = false;
    private final FileTreePanel treePanel;

    public FileTreeContextMenu(JTree tree, FileTreePanel treePanel) {
        this.treePanel = treePanel;
        tree.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                if (SwingUtilities.isRightMouseButton(e)) {
                    int row = tree.getClosestRowForLocation(e.getX(), e.getY());
                    tree.setSelectionRow(row);
                    showContextMenu(tree, e.getX(), e.getY());
                }
            }
        });
    }

    public FileTreeContextMenu(JTree tree) {
        this(tree, null);
    }

    private void showContextMenu(JTree tree, int x, int y) {
        JPopupMenu popupMenu = new JPopupMenu();
        JMenuItem newItem = new JMenuItem("新建文件夹");
        JMenuItem renameItem = new JMenuItem("重命名");
        JMenuItem deleteItem = new JMenuItem("删除");
        JMenuItem copyItem = new JMenuItem("复制");
        JMenuItem cutItem = new JMenuItem("剪切");
        JMenuItem pasteItem = new JMenuItem("粘贴");
        newItem.addActionListener(e -> createNewFolder(tree));
        renameItem.addActionListener(e -> renameNode(tree));
        deleteItem.addActionListener(e -> deleteNode(tree));
        copyItem.addActionListener(e -> copyFile(tree, false));
        cutItem.addActionListener(e -> copyFile(tree, true));
        pasteItem.addActionListener(e -> pasteFile(tree));
        popupMenu.add(newItem);
        popupMenu.add(renameItem);
        popupMenu.add(deleteItem);
        popupMenu.addSeparator();
        popupMenu.add(copyItem);
        popupMenu.add(cutItem);
        popupMenu.add(pasteItem);
        popupMenu.show(tree, x, y);
    }

    private void copyFile(JTree tree, boolean isCut) {
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
        if (selectedNode == null) return;
        File selectedFile = getFileFromNodeWithRoot(selectedNode);
        clipboardFile = selectedFile;
        isCutOperation = isCut;
        String type = isCut ? "剪切" : "复制";
        JOptionPane.showMessageDialog(tree, type + "了: " + selectedFile.getName());
    }

    private void pasteFile(JTree tree) {
        if (clipboardFile == null) return;
        DefaultMutableTreeNode targetNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
        if (targetNode == null) return;
        File targetDir = getFileFromNodeWithRoot(targetNode);
        if (!targetDir.isDirectory()) {
            JOptionPane.showMessageDialog(tree, "请选择一个文件夹进行粘贴");
            return;
        }
        File destFile = new File(targetDir, clipboardFile.getName());
        try {
            FileOperations.copyFile(clipboardFile, destFile);
            if (isCutOperation) {
                FileOperations.deleteFileOrDirectory(clipboardFile);
                isCutOperation = false;
            }
            targetNode.add(new DefaultMutableTreeNode(destFile.getName()));
            ((DefaultTreeModel) tree.getModel()).reload(targetNode);
            clipboardFile = null;
            JOptionPane.showMessageDialog(tree, "粘贴成功！");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(tree, "粘贴失败: " + ex.getMessage());
        }
    }

    private void createNewFolder(JTree tree) {
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
        if (selectedNode == null) return;
        String folderName = JOptionPane.showInputDialog(tree, "输入新文件夹名称：");
        if (folderName == null || folderName.trim().isEmpty()) return;
        File parentDir = getFileFromNodeWithRoot(selectedNode);
        if (!parentDir.isDirectory()) {
            JOptionPane.showMessageDialog(tree, "请选择一个文件夹作为父目录");
            return;
        }
        if (FileOperations.createFolder(parentDir, folderName)) {
            selectedNode.add(new DefaultMutableTreeNode(folderName));
            ((DefaultTreeModel) tree.getModel()).reload(selectedNode);
            JOptionPane.showMessageDialog(tree, "新建文件夹成功");
        } else {
            JOptionPane.showMessageDialog(tree, "新建文件夹失败");
        }
    }

    private void renameNode(JTree tree) {
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
        if (selectedNode == null || selectedNode.isRoot()) return;
        File oldFile = getFileFromNodeWithRoot(selectedNode);
        String newName = JOptionPane.showInputDialog(tree, "输入新名称：", selectedNode.getUserObject());
        if (newName == null || newName.trim().isEmpty()) return;
        File newFile = new File(oldFile.getParent(), newName);
        if (FileOperations.renameFile(oldFile, newFile)) {
            selectedNode.setUserObject(newName);
            ((DefaultTreeModel) tree.getModel()).reload((TreeNode) selectedNode.getParent());
            JOptionPane.showMessageDialog(tree, "重命名成功");
        } else {
            JOptionPane.showMessageDialog(tree, "重命名失败");
        }
    }

    private void deleteNode(JTree tree) {
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
        if (selectedNode == null || selectedNode.isRoot()) return;
        int confirm = JOptionPane.showConfirmDialog(tree, "确认删除吗？", "提示", JOptionPane.YES_NO_OPTION);
        if (confirm != JOptionPane.YES_OPTION) return;
        File file = getFileFromNodeWithRoot(selectedNode);
        boolean success = FileOperations.deleteFileOrDirectory(file);
        if (success) {
            DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selectedNode.getParent();
            parent.remove(selectedNode);
            ((DefaultTreeModel) tree.getModel()).reload(parent);
            JOptionPane.showMessageDialog(tree, "删除成功");
        } else {
            JOptionPane.showMessageDialog(tree, "删除失败");
        }
    }

    private File getFileFromNodeWithRoot(DefaultMutableTreeNode node) {
        if (treePanel != null) {
            return FileUtils.getFileFromNode(node, treePanel.getCurrentRootFile());
        } else {
            return FileUtils.getFileFromNode(node);
        }
    }
} 